package com.ophiux.config;

import org.apache.http.HttpHost;
import org.apache.lucene.index.Terms;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.util.Map;

public class SearchTest {

    private RestHighLevelClient client;

    @BeforeEach
    public void init() {
        this.client = new RestHighLevelClient(RestClient.builder(
                new HttpHost("http://192.168.30.128", 9200)
        ));
    }

    @AfterEach
    public void close() throws IOException {
        this.client.close();
    }

    /**
     * matchall查询
     * @throws IOException
     */
    @Test
    public void testMatchAll() throws IOException {

        SearchRequest searchRequest = new SearchRequest("hhlindex");

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchAllQuery());
//        searchRequest.source(searchSourceBuilder);
        searchRequest.source().query(QueryBuilders.matchAllQuery()).from(0).size(5);

        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits searchHits = response.getHits();
        //总条数
        long total = searchHits.getTotalHits().value;
        SearchHit[] hits = searchHits.getHits();
        for (SearchHit hit : hits) {
            String json = hit.getSourceAsString();
            System.out.println(json);
        }
    }

    /**
     * match查询
     * @throws IOException
     */
    @Test
    public void testMatch() throws IOException {
        SearchRequest searchRequest = new SearchRequest("hhlindex");
        searchRequest.source().query(QueryBuilders.matchQuery("userName","hhl"));

        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits searchHits = response.getHits();
        //总条数
        long total = searchHits.getTotalHits().value;
        SearchHit[] hits = searchHits.getHits();
        for (SearchHit hit : hits) {
            String json = hit.getSourceAsString();
            System.out.println(json);
        }
    }

    /**
     * Boolean查询
     * @throws IOException
     */
    @Test
    public void testBoolean() throws IOException {
        SearchRequest searchRequest = new SearchRequest("hhlindex");
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(QueryBuilders.termQuery("city","重庆"));
        boolQueryBuilder.filter(QueryBuilders.rangeQuery("age").lte(20));//小于20岁

        searchRequest.source().query(boolQueryBuilder);

        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits searchHits = response.getHits();
        //总条数
        long total = searchHits.getTotalHits().value;
        SearchHit[] hits = searchHits.getHits();
        for (SearchHit hit : hits) {
            String json = hit.getSourceAsString();
            System.out.println(json);
        }
    }



    /**
     * 高亮
     * @throws IOException
     */
    @Test
    public void testHightlight() throws IOException {

        SearchRequest searchRequest = new SearchRequest("hhlindex");
        searchRequest.source().query(QueryBuilders.matchQuery("all","hhl"));

        searchRequest.source().highlighter(new HighlightBuilder()
                .field("name")
                //是否需要与查询 字段匹配
                .requireFieldMatch(false)
        );

        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits searchHits = response.getHits();
        //总条数
        long total = searchHits.getTotalHits().value;
        SearchHit[] hits = searchHits.getHits();
        for (SearchHit hit : hits) {
            String json = hit.getSourceAsString();
            System.out.println(json);
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField highlightField = highlightFields.get("name");
            Text[] fragments = highlightField.getFragments();
            String name = fragments[0].string();

            //重新复制给对象name属性
        }
    }

    /**
     * 聚合
     * @throws IOException
     */
    @Test
    public void testAggregation() throws IOException {
        SearchRequest searchRequest = new SearchRequest("indexName");

        searchRequest.source().size(0);
        searchRequest.source().aggregation(AggregationBuilders
                .terms("brandAgg")
                .field("userName")
                .size(10)
        );

        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        //解析结果
        Aggregations aggregations = response.getAggregations();
        Terms brandTerms = aggregations.get("brandAgg");//根据聚合名称，返回聚合结果
        //。。。。。。省略
    }

}
